<template>
	<div>
		<Content>
			<Spin style="position:fixed;top:0;left:0;width:100%;height:100%;z-index: 9999990;" fix v-if="showSpin">
				<Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
				<div>上传中</div>
			</Spin>
			<Form :label-width="140">
				<h1>基本信息</h1>
				<FormItem label="课程名称" required>
					<Input class="view-input" v-model="formData.spuName" placeholder="请输入课程名称"></Input>
				</FormItem>
				<FormItem label="讲师姓名" required>
					<Input class="view-input" v-model="skuInfo.skuModel" placeholder="请输入讲师姓名"></Input>
				</FormItem>
				<FormItem label="认证机构" required>
					<Input class="view-input" v-model="formData.productionPlace" placeholder="请输入认证机构"></Input>
				</FormItem>
				<FormItem label="课程内容描述">
					<Input class="view-input" :max="128" placeholder="请输入租车规则或说明" v-model="formData.industrialName" />
				</FormItem>
				<FormItem label="商品标签">
					<Input class="view-input" :max="64" placeholder="多个标签请用空格分隔，如：投资 乡村 实战" v-model="formData.viewLabel" />
				</FormItem>
				<FormItem label="商品分类" required>
					<Cascader class="view-input" :data="category" v-model="categoryArray" :load-data="loadData"></Cascader>
				</FormItem>
				<FormItem label="课程资源" required>
					<template>
						<div class="demo-upload-list" v-for="(item,index) in spuUploadList" :key="index">
							<template v-if="item.status === 'finished'">
								<img :src="item.src" alt="img">
								<div class="demo-upload-list-cover">
									<Icon type="ios-eye-outline" @click.native="handleView(item.src)" title="预览"></Icon>
									<Icon type="ios-trash-outline" @click.native="handleRemove(index)" title="删除"></Icon>
								</div>
							</template>
							<template v-else>
								<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
							</template>
						</div>
						<Upload ref="spu_upload"
							:show-upload-list="false"
							:on-success="onUploadSuccess"
							:format="['jpg','jpeg','png']"
							:max-size="4096"
							:on-format-error="imageFormatError"
							:on-exceeded-size="imageMaxSize"
							:before-upload="imageBeforeUpload"
							type="drag"
							name="binaryFile"
							:headers="uploadHeader"
							:data="uploadParam"
							:action="uploadApi"
							style="display: inline-block;width:58px;">
							<div style="padding:8px 0;line-height:20px">
								<Icon type="ios-camera" size="20"></Icon><br>封面
							</div>
						</Upload>
					</template>
					<template>
						<div class="demo-upload-list" v-for="(item,index) in videoUploadList" :key="index">
							<template v-if="item.status === 'finished'">
								<img src="../../../images/video-icon.png" alt="img">
								<div class="demo-upload-list-cover">
									<!-- <Icon type="ios-eye-outline" @click.native="handleView(item.src)" title="预览"></Icon> -->
									<Icon type="ios-trash-outline" @click.native="videoRemove(index)" title="删除"></Icon>
								</div>
							</template>
							<template v-else>
								<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
							</template>
						</div>
						<Upload ref="video_upload"
							:show-upload-list="false"
							:on-success="onUploadSuccess"
							:format="['mp4','mov','m4v','3gp','avi','m3u8']"
							:max-size="51200"
							:on-format-error="videoFormatError"
							:on-exceeded-size="videoMaxSize"
							:before-upload="videoBeforeUpload"
							type="drag"
							name="binaryFile"
							:headers="uploadHeader"
							:data="uploadParam"
							:action="uploadApi"
							style="display: inline-block;width:58px;">
							<div style="padding:8px 0;line-height:20px">
								<Icon type="ios-camera" size="20"></Icon><br>视频
							</div>
						</Upload>
					</template>
				</FormItem>
			</Form>
			<Form :label-width="150" inline>
				<FormItem label="单价(元)" required>
					<InputNumber :min="0" placeholder="请输入课程单价" class="view-input" v-model="skuInfo.salesPrice"
					 :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" 
					 :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
					/>
				</FormItem>
				<FormItem label="原价(元)" required>
					<InputNumber :min="0" placeholder="请输入市场价或原价" class="view-input" v-model="skuInfo.aroundPrice"
					 :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" 
					 :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
					/>
				</FormItem>
				<FormItem label="计价单位" required>
					<Input placeholder="请输入计价单位" class="view-input" v-model="skuInfo.skuUom" />
				</FormItem>
				<FormItem label="试看时长（秒）" required>
					<InputNumber :min="0" placeholder="请输入试看时长" class="view-input" v-model="formData.previewTimeLimit" />
				</FormItem>
			</Form>
			<h1>其它内容</h1>
			<template>
				<article id="editorContainer" style="margin-top:30px;margin-left:140px"></article>
			</template>
			<Form>
				<FormItem style="position:fixed;z-index:999999;bottom: 10px;right:50px">
					<Button type="primary" @click="Submit">保存</Button>
				</FormItem>
			</Form>
		</Content>
		<Modal title="View Image" v-model="visible">
			<img :src="imgName" v-if="visible" style="width: 100%">
		</Modal>
	</div>
</template>
<script>
import E from '@/libs/SourceCodeEditor'
export default {
	name: 'GoodsCreate',
	props: {
		callbank: Function,
    seletions: Array
	},
	data() {
		return {
			showSpin: false,
			orgFreeze: this.$store.getUser('userType') !== 9,
			skuImageUpload: [],
			uploadApi: `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`,
			uploadHeader: {
				'Authorization': 'Bearer ' + this.$store.getToken()
			},
			uploadParam: {
				catalog:'goods'
			},
			skuInfo: {
				inventory: 1,
				salesPrice: 0,
				systemPrice: 0
			},
			formData: {
				orgId: this.$store.getOrg('orgId'),
				orgName: this.$store.getOrg('orgName'),
				shopId: this.$store.getShop('shopId'),
				shopName: this.$store.getShop('shopName'),
				salesModel: this.$store.getShop('shopType'),
				storeId: this.$store.getWms('warehouseId'),
				warehouseName: this.$store.getWms('warehouseName'),
				regionCode: this.$store.getWms('countyCode'),
				outputRate: 0,
				inputRate: 0,
				wholesalePrice: 0.00,
				profitRate: 0,
				spuImage: null,
				spuName: null, //商品名称
				categoryId: null, //类目id
				spuType: 9, //商品类型：0 零售商品，1 批发商品，2 产权交易，3 电子卡券，4积分商品，5限时抢购，6旅游产品，7租车，8乡村活动，9视频课程
				groupId: null,
				miniBuy: 1, //多少件起售
				spuSort: 9, //排序
				spuFlag: 9, //虚拟商品
				spuArticle: null,
				previewTimeLimit: 30, //试看时长（秒）
				skuList: []
			},
			imgName: null,
			visible: false,
			spuUploadList: [],
			videoUploadList: [],
			categoryArray: [],
			category: [],
			editor: null
		}
	},
	watch: {
		categoryArray(val) {
			if(val.length > 1) {
				let index = val.length - 1
				this.formData.categoryId = val[index]
				this.formData.categoryPath = val.slice(0,-1).join('/')
			} else {
				this.formData.categoryId = val[0]
				this.formData.categoryPath = '/'
			}
		}
	},
	computed: {
		
	},
	methods: {
		Init(){
			this.getCategoryList()
		},
		getCategoryList(){
			new this.$rest({
				service: 'agroerp-shop',
				 gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal:{
						categoryType: 0
					}
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.category = data
					} else {
						this.$Notice.warning({
							title: '商品分类获取失败',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		loadData (item, callback) {
			item.loading = true;
			new this.$rest({
				service: 'agroerp-shop',
				gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal: {
						categoryPid: item.value,
						categoryType: 0
					},
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false;
                    callback();
					} else {
						this.$Notice.warning({
							title: '商品分组获取失败2',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		handleView(src) {
			this.$Modal.info({
				content: `<img style="width:100%" src="${src}">`,
				width: '500px',
			})
		},
		handleRemove(id) {
			this.spuUploadList.splice(id, 1)
		},
		videoRemove(id) {
			this.videoUploadList.splice(id, 1)
		},
		imageFormatError(file) {
			this.$Notice.warning({
				title: '图片格式不支持',
				desc: `${file.name}图片格式不支持，请使用jpg、jpeg、png格式`
			})
		},
		videoFormatError(file) {
			this.$Notice.warning({
				title: '视频格式不支持',
				desc: `${file.name}视频格式不支持，请使用mp4,mov,m4v,3gp,avi,m3u8格式`
			})
		},
		imageMaxSize(file) {
			this.$Notice.warning({
				title: '图片过大',
				desc: `${file.name}图片大小不能超过2M`
			})
		},
		videoMaxSize(file) {
			this.$Notice.warning({
				title: '视频过大',
				desc: `${file.name}视频资源不能超过50M`
			})
		},
		onUploadSuccess(response, file, fileList) {
			if(response.code == 20000){
				fileList.forEach(element => {
					element.src = element.response.data.protocol + element.response.data.hostName + element.response.data.filePath
				})
				this.showSpin = false
			} else {
				this.$Notice.warning({
					title: '上传失败',
					desc: `失败原因：${response.msg}`
				})
			}
		},
		imageBeforeUpload(file) {
			window.URL = window.URL || window.webkitURL
			const check = this.spuUploadList.length > 0
			if (check) {
				this.$Notice.warning({
					title: '只能上传1个视频封面'
				})
			}
			return !check
		},
		videoBeforeUpload(file) {
			window.URL = window.URL || window.webkitURL
			const check = this.videoUploadList.length > 0
			if (check) {
				this.$Notice.warning({
					title: '只能上传1个视频资源'
				})
				return false
			}
			this.showSpin = true
			return true
		},
		Submit() {
			if(this.spuUploadList.length === 0) {
				this.$Notice.warning({
					title: '必填项为空',
					desc: `请上传视频封面图`
				})
				return false
			}
			if(this.videoUploadList.length === 0) {
				this.$Notice.warning({
					title: '必填项为空',
					desc: `请上传视频资源`
				})
				return false
			}

			let goodsAlbum = []
			this.spuUploadList.forEach(element => {
				let album = new Object()
				album.src = element.src
				album.type = 0
				goodsAlbum.push(album)
			})
			this.formData.goodsAlbum = JSON.stringify(goodsAlbum)
			this.skuInfo.specEntityList = [
				{specName:'讲师名称',specValue:this.skuInfo.skuModel},
				{specName:'机构认证',specValue:this.formData.productionPlace}
			]
			this.skuInfo.skuImage = this.spuUploadList[0].src
			this.formData.skuList.length = 0
			this.formData.skuList.push(this.skuInfo)
			this.formData.spuImage = this.spuUploadList[0].src
			this.formData.videoSrc = this.videoUploadList[0].src
			this.formData.spuArticle = this.editor.txt.html()

			new this.$rest({
				gateway: 'agroerp',
				service: "agroerp-shop",
				url: '/v1.0/agromall/create/basic/sku',
				data: {
					pojo: this.formData,
				},
				action: (res) => {
					if (res.data.code === 20000) {
						this.callbank()
					} else {
						this.$Notice.warning({
							title: "操作失败",
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).post()
		},
		initEditor() {
			this.editor = new E('#editorContainer')
			this.editor.config.height = 800
			this.editor.config.placeholder = '视频课程详情介绍'
			this.editor.config.uploadImgServer = `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`
			this.editor.config.uploadImgMaxSize = 1 * 1024 * 1024
			this.editor.config.uploadImgMaxLength = 1
			this.editor.config.uploadFileName = 'binaryFile'
			this.editor.config.uploadImgParams = {
				catalog:'goods',
				selfName: false
			}
			this.editor.config.uploadImgHeaders = {
				'Authorization': 'Bearer ' + this.$store.getToken()
			}
			this.editor.config.uploadImgHooks = {
				success: (xhr)=>{
					console.log('图片插入成功',xhr)
				},
				fail: (xhr, editor, resData)=>{
					console.log('fail', resData)
					this.$Message.error('图片插入时出错')
				},
				error: (xhr, editor, resData)=>{
					console.log('error', xhr, resData)
					this.$Message.error('http请求异常')
				},
				timeout: (xhr)=>{
					console.log('timeout')
					this.$Message.error('上传超时')
				},
				customInsert: (insertImgFn, result)=>{
					console.log('result ->',result)
					if(result.code === 20000){
						insertImgFn(result.data.protocol + result.data.hostName+ result.data.filePath)
					} else {
						this.$Notice.error({
							title: '上传失败',
							desc: `原因：${result.msg}`
						})
					}
				}
			}
			this.editor.create()
		}
	},
	created(){
		
	},
	mounted() {
		this.spuUploadList = this.$refs.spu_upload.fileList
		this.videoUploadList = this.$refs.video_upload.fileList

		//初始化富文本编辑器
		this.initEditor()
	},
	beforeUnmount() {
		this.editor.destroy()
	}
}
</script>
<style lang="less" scoped>
table{
	th {
    border: 1px solid #ccc;
    min-width: 50px;
    height: 20px;
        background-color: yellow;
    }
}

h1 {
	background-color: #f5f5f5; font-size: 18px;
	padding: 10px;
	color: #333;
	margin-bottom: 18px;
}

.view-input {
	width: 100%;
}

.vertical-center-modal {
	display: flex;
	align-items: center;
	justify-content: center;
}

.demo-upload-list {
	display: inline-block;
	width: 60px;
	height: 60px;
	background: #fff;
	position: relative;
}

.demo-upload-list img {
	width: 100%;
	height: 100%;
	border-radius: 4px;
	box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
}

.demo-upload-list-cover {
	display: none;
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
	display: block;
}

.demo-upload-list-cover i {
	color: #fff;
	font-size: 20px;
	cursor: pointer;
	margin: 0 2px;
}

.intro-con {
	min-height: 140px;
}

.draggable-btn {
	margin-top: 20px;
}

.code-con {
	width: 400px;
	background: #F9F9F9;
	padding-top: 10px;
}

.goods-type div.box-in {
	border: 1px solid #d9c9c6;
	text-align: center;
	cursor: pointer;
	height: 60px;
	position: relative;
}

.goods-type div.box-in>img {
	width: 25%;
	height: 50%;
	position: absolute;
	bottom: 0;
	right: 0;
}

.category-params {
	background-color: #f5f5f5;
	padding: 10px;
}

.button-addSpec {
	width: 98%;
	background-color: #f5f5f5;
	margin: 10px auto;
	padding: 8px;
}
.spec-item {
	display: inline-block; vertical-align: top; position: relative;
}
.have-img {
	height: 110px;
}
.spec-item:hover .del-spec {
	display: block;
}
.spec-item .del-spec {
	position: absolute; top: -8px; right: 0; width: 20px; z-index: 99; opacity: .5; display: none; cursor: pointer;
}
.spec-item .ivu-upload {
	position: absolute; top: 40px; left: 22px;
}
.spec-img {
	margin-top: 5px;
}
.spec-img>img {
	width: 100px; height: 80px; border-radius: 5px; border: 2px solid #FFFFFF;
}
.spec-img>img:hover {
	box-shadow: 0 0 7px #00000050;
}
footer {
	position: fixed; width: auto; bottom: 25px; left: 200px; right: 0; text-align: center; z-index: 999999;
}

th .ivu-table-cell {
	white-space: nowrap;
}
.ivu-table-cell {
	white-space: nowrap;
}
.skuTab b {
	padding: 0 10px; cursor: pointer;
}

.demo-spin-icon-load{
	animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
	from { transform: rotate(0deg);}
	50%  { transform: rotate(180deg);}
	to   { transform: rotate(360deg);}
}
.demo-spin-col{
	height: 100px;
	position: relative;
	border: 1px solid #eee;
}
</style>
